//
//  HJWebViewController.m
//  KaiChat
//
//  Created by lx on 2023/10/17.
//

#import "HJWebViewController.h"
#import <WebKit/WebKit.h>
#import "HJMinePresent.h"
#import "TJEmptyDataHandler.h"

@interface HJWebViewController ()<WKNavigationDelegate>

@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) TJEmptyDataHandler *emptyDataHandler;

@end

@implementation HJWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationBar.backgroundColor = UIColor.whiteColor;
    self.navigationBar.title = self.title;
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.applicationNameForUserAgent = getUserAgent();
    self.webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
    self.webView.navigationDelegate = self;
    [self.view addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.offset(KNavBarHight);
    }];

    self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    self.progressView.frame = CGRectMake(0, 0, self.view.frame.size.width, 2);
    self.progressView.progressTintColor = [UIColor tj_mainColor];
    self.progressView.trackTintColor = [UIColor clearColor];
    [self.navigationBar addSubview:self.progressView];
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.offset(2);
    }];
     
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
    
    if (_type == HJWebViewTypeService) {
        [HJMinePresent getAgreementComplete:^(NSString * _Nullable url) {
            self.url = url;
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.kaichat.io/m/app-service"]];
            [self.webView loadRequest:request];
        }];
    } else {
        if (_type == HJWebViewTypePay) {
            _emptyDataHandler = [TJEmptyDataHandler emptyDataHandleWithScrollView:self.webView.scrollView configuration:^TJEmptyDataType(TJEmptyDataModel * _Nonnull dataModel) {
                dataModel.text = @"Loading error";
                return TJEmptyDataTypeBase;
            }];
        }
        
        if (_type == HJWebViewTypeHelp) {
            HJBarButton *closeButton = [HJBarButton barButtonWithImage:[UIImage imageNamed:@"nav_close"] target:self action:@selector(didClickCloseButton)];
            [self.navigationBar.contentView addSubview:closeButton];
            [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.height.offset(32);
                make.centerY.offset(0);
                make.left.equalTo(self.navigationBar.backBarButton.mas_right);
            }];
        }
        
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_url]];
        [self.webView loadRequest:request];
    }
    
}

- (void)didClickCloseButton {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    TJLog(@"withError = %@", error);
    self.progressView.hidden = YES;
    _emptyDataHandler.canDisplay = YES;
    [self.emptyDataHandler reloadEmptyDataSet];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    TJLog(@"%s, absoluteString = %@, self.title = %@, %@", __func__, self.url, self.title, webView.title);
    if (!self.title && _type != HJWebViewTypePay) {
        self.navigationBar.title = webView.title;
    }
    
    if (_type == HJWebViewTypePay) {
        NSString *jsCode = [NSString stringWithFormat:@"window.content = '%@';", _content];
        [self.webView evaluateJavaScript:jsCode completionHandler:^(id result, NSError *error) {
            if (error) {
                TJLog(@"JavaScript execution error: %@", [error localizedDescription]);
            } else {
                TJLog(@"JavaScript executed successfully");
            }
        }];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"] && object == self.webView) {
        CGFloat estimatedProgress = self.webView.estimatedProgress;
        [self.progressView setProgress:estimatedProgress animated:YES];
        if (estimatedProgress >= 1.0) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(750 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
                self.progressView.hidden = YES;
            });
        }
    }
}

- (void)popViewController {    
    if (self.webView.canGoBack) {
        [self.webView goBack];
    } else {
        [super popViewController];
    }
}

- (UIModalPresentationStyle)modalPresentationStyle {
    return UIModalPresentationFullScreen;
}

- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

@end

 
